import sys
from pathlib import Path
import streamlit as st
import requests

# -------------------------- 项目根目录配置 --------------------------
app_py_path = Path(__file__).resolve()
project_root = app_py_path.parent.parent.parent

if str(project_root) not in sys.path:
    sys.path.insert(0, str(project_root))

# 配置导入
try:
    from config.app_config import get_app_config

    config = get_app_config()
    API_BASE_URL = f"http://{config.api_host}:{config.api_port}"
    QA_API_URL = f"{API_BASE_URL}/qa/query"
except ImportError as e:
    st.error("无法加载配置文件，请检查项目结构")
    st.stop()


def main():
    # 页面配置
    st.set_page_config(
        page_title="知识库问答",
        layout="wide",
        initial_sidebar_state="collapsed"  # 折叠侧边栏
    )

    # 页面标题
    st.title("📚 知识库问答系统")
    st.markdown("---")

    # 初始化会话状态（仅保留必要项）
    if "last_answer" not in st.session_state:
        st.session_state.last_answer = None
    if "last_question" not in st.session_state:
        st.session_state.last_question = None

    # 获取默认配置
    try:
        config_response = requests.get(f"{API_BASE_URL}/qa/config", timeout=5)
        default_top_k = config_response.json().get("default_top_k", 3)
    except:
        default_top_k = 3

    # 问题输入区域
    st.subheader("请输入您的问题")
    question = st.text_area(
        label="问题输入框",
        placeholder="例如：请问周转天数是怎么计算的？",
        height=120,
        key="question_input",
        label_visibility="hidden"
    )

    # 高级参数设置（移除后端服务显示）
    with st.expander("🔧 高级设置", expanded=False):
        # 仅保留检索数量设置，删除后端服务信息列
        top_k = st.slider(
            "检索相关文档数量",
            min_value=1,
            max_value=10,
            value=default_top_k,
            help="数值越大，参考的文档范围越广（不影响显示内容）"
        )

    # 查询按钮
    if st.button("获取答案", type="primary", use_container_width=True):
        if not question.strip():
            st.warning("请输入问题内容后再查询", icon="⚠️")
            return

        with st.spinner("正在检索相关知识并生成答案..."):
            try:
                # 调用API获取答案（后端交互逻辑保留，但不显示给用户）
                response = requests.post(
                    QA_API_URL,
                    json={"question": question, "top_k": top_k},
                    timeout=60
                )
                response.raise_for_status()
                result = response.json()

                st.session_state.last_question = question
                st.session_state.last_answer = result["answer"]
                st.rerun()

            except requests.exceptions.Timeout:
                st.error("请求超时，请尝试更简短的问题或稍后再试", icon="⏰")
            except Exception as e:
                st.error(f"获取答案失败：{str(e)}", icon="❌")

    # 显示历史答案
    if st.session_state.last_answer:
        st.markdown("---")
        st.subheader("💡 回答结果")

        # 显示问题
        with st.container(border=True):
            st.info(f"问题：{st.session_state.last_question}", icon="❓")

        # 显示答案
        with st.container(border=True):
            st.write(st.session_state.last_answer)

    # 底部提示信息
    st.markdown("---")
    st.caption("提示：输入问题并点击「获取答案」按钮，系统会基于知识库内容进行回答")


if __name__ == "__main__":
    main()